import express, { Request, Response } from 'express';
import { SensorHourlyData } from '../entity/SensorHourlyData';
import { AppDataSource } from '../config/database';
import { authenticateJWT } from '../middleware/authMiddleware';
import { Between } from 'typeorm';

const router = express.Router();

/**
 * 查询设备最近24小时某指标的传感器记录
 */
router.get('/sensor-data/last24h', authenticateJWT, async (req: Request, res: Response) => {
  const userId = (req as any).user.userId;
  const deviceId = req.query.device_id as string;
  const metricType = req.query.metric_type as string;

  if (!deviceId || !metricType) {
      res.status(400).json({ message: '缺少参数 device_id 或 metric_type' });
      return;
  }

  try {
    const now = new Date();
    const start = new Date(now);
    start.setHours(start.getHours() - 24);
    start.setMinutes(0, 0, 0);

    const repo = AppDataSource.getRepository(SensorHourlyData);

    const records = await repo.find({
      where: {
        deviceId,
        metricType,
        hourStart: Between(start, now)
      },
      order: {
        hourStart: 'ASC'
      }
    });

     res.json({
      device_id: deviceId,
      metric_type: metricType,
      data: records.map(r => ({
        hour: r.hourStart.toISOString(),
        value: r.metricValue
      }))
    }); return;
  } catch (err: any) {
     res.status(500).json({ message: '查询失败', error: err.message });
     return;
  }
});

export default router;
